var app = getApp();
var util = require('../../utils/util.js');
var addressList = null;
Page({
  data: {
    freight:0,//运费

    // 规格数量框
    flag: 0,//点选规格时来源 0：规格点 1：立即购买 2：加入购物车
    pAndNList:[],
    count:0,
    selectName: "",//已选的属性名字
    selectAttrid: [],//选择的属性id
    //商品信息
    goods_info: {},
    // banner
    imgUrls: [
  
    ],
    point:0,
    indicatorDots: true, //是否显示面板指示点
    autoplay: true, //是否自动切换
    interval: 3000, //自动切换时间间隔,3s
    duration: 1000, //  滑动动画时长1s
    quest_modal: "none",
    // 商品详情介绍
    deschtml:"",
    index:0,
    buyMethod:1,
    shoucang:false
  },
  onLoad: function (options) {
    var that = this;
    //获取手机高度
    this.setData({
      navH: app.globalData.navHeight,
      time: util.formatTime(new Date()),
      cardNo: options.cardNo,//卡号
      pickUpGoodCode: options.pickUpGoodCode,//提货码
      address: options.address,
      telephone: options.telephone,
      username: options.username,
    })
    if (options.partnerUserId == undefined) {
      that.setData({
        partnerUserId: 0
      })
    } else {
      that.setData({
        partnerUserId: options.partnerUserId
      })
    }
    let endTimeList = [];
    that.setData({
    });
    wx.request({
      url: app.globalData.url + "getProductDetailByProductId",
      data: {
        productId: options.productid,
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data.data;
        // var list = res.data.list; 
        var questionProducts = res.data.questionProducts;
        var imgs = [];
        var pcount = res.data.data.product.inventoryQuantity;
        // for (var i = 0; i < list.length; i++) {
        //   imgs[i] = list[i].coverUrl;
        // }
        if (that.data.type == 1) {
          //秒杀
          console.log(data.product)
          that.setData({
            producData: data.product,
            deschtml: data.detail,
            imgUrls: imgs,
            count: pcount,
            originalPrice: data.product.price,
            price: data.product.price,
            point: data.product.minPoint,
            thumbnailImage: data.product.thumbnailImage,
            seckillEndTime: data.product.seckillEndTime,
            seckillNum: data.product.seckillLimitNum,
            productId: data.product.productId,
            productTypeId: data.product.productTypeId,
            listProduct: questionProducts,
            minPrice: data.product.minPrice,
          })
          that.countTime(that.data.seckillEndTime)
        } else {
          that.setData({
            producData: data.product,
            deschtml: data.detail,
            imgUrls: imgs,
            count: pcount,
            originalPrice: data.product.originalPrice,
            price: data.product.price,
            point: data.product.minPoint,
            thumbnailImage: data.product.thumbnailImage,
            seckillEndTime: data.product.seckillEndTime,
            seckillNum: data.product.seckillLimitNum,
            productId: data.product.productId,
            productTypeId: data.product.productTypeId,
            listProduct: questionProducts,
            minPrice: data.product.minPrice,
          })
          if (that.data.seckillEndTime != undefined) {
            that.countTime(that.data.seckillEndTime)
          }

        }
        that.setData({
          gropuShopList: 0
        })
        wx.request({
          url: app.globalData.url + "getCouponListBy",
          data: {
            productId: data.product.productId,
            productTypeId: data.product.productTypeId,
            userId: wx.getStorageSync("userId"),
          },
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {
            that.setData({
              cpdata: res.data.data
            })
            if (res.data.data.length >= 1) {
              that.setData({
                cpdatathreshold: res.data.data[0].threshold,
                cpdataprice: res.data.data[0].price
              })
            }
            if (res.data.data.length >= 2) {
              that.setData({
                cpdatathreshold1: res.data.data[1].threshold,
                cpdataprice1: res.data.data[1].price,
              })
            }

          },
        })
      },
    })
    wx.request({
      url: app.globalData.url + 'getProductEvaluation',
      data: { productId: options.productid },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: function (res) {
        that.setData({
          evaluationList: res.data.data.reverse(),
        });
        for (var i = 0; i < that.data.evaluationList.length;i++){
          that.data.evaluationList[i].reviewContent = that.entitiesToUtf16(that.data.evaluationList[i].reviewContent)
        }
        that.setData({
          evaluationList: that.data.evaluationList
        });
        var imgArr = [];
        for (var i = 0; i < res.data.data.length; i++) {
          var evaImg = res.data.data[i].reviewImages;
          var arr1 = evaImg.split(';;;');
          if (arr1[arr1.length - 1].trim() == "") {
            arr1.length = arr1.length - 1;
          }
          imgArr.push(arr1);
        }
        that.setData({
          imageList: imgArr,
        });
      }
    });

  },
  onShow:function(){
    var that = this;
  },
  onReady: function () {
    var that = this;
    that.interval();
  },
  //预览图片
  previewImage: function (e) {
    var current = e.target.dataset.src;

    wx.previewImage({
      current: current, // 当前显示图片的http链接  
      urls: this.data.imgUrls // 需要预览的图片http链接列表  
    })
  },
  // 收藏
  addLike() {
    this.setData({
      isLike: !this.data.isLike
    });
    
  },
    bindManual :function(e){
    this.setData({
      num: e.detail.value
    })
  },
  // 跳到购物车
  toCar() {
    wx.switchTab({
      url: '/pages/shoppingCart/shoppingCart?userId=' + this.data.producData.userId
    })
  },
  immeBuy(e) {
    var that = this;
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          if (that.data.producData.seckillLimitNum != 0) {
            if (that.data.num > that.data.producData.seckillLimitNum) {
              wx.showToast({
                title: "超过限购数量",
                icon: 'none',
                duration: 2000
              })
              return;
            }
          }

          if (that.data.flag == 1) {
            wx.request({
              url: app.globalData.url + "modifyShoppingCart",//给函数传递服务器地址参数 
              data: {
                productId: that.data.producData.productId,
                userId: wx.getStorageSync("userId"),
                num: that.data.num,
              },//给服务器传递数据，本次请求不需要数据，可以不填
              header: {
                'content-type': 'application/json' // 默认值，返回的数据设置为json数组格式
              },
              success: function (res) {//打印出返回的数据
                //that.toCar();
                // that.toCar();
                if (res.data.result == 0) {
                  wx.showToast({
                    title: '' + res.data.errmsg,
                    icon: 'none',
                    duration: 2000
                  })
                } else {
                  wx.showToast({
                    title: '加入购物车成功',
                    icon: 'success',
                    duration: 2000
                  });
                }
              }
            })

          } else if (that.data.flag == 2) {
            if (that.data.point == undefined) {
              that.setData({
                point: 0
              })
            }
            if (that.data.typeShow == 2) {
              var plist = '[{"productId":"' + that.data.producData.productId + '","num":' + that.data.num + ',"price":' + that.data.groupShoppingPrice + ',"title":"' + that.data.producData.title + '","thumbnailImage":"' + that.data.producData.thumbnailImage + '","point":' + that.data.point + '}]';
            } else {
              var plist = '[{"productId":"' + that.data.producData.productId + '","num":' + that.data.num + ',"price":' + that.data.minPrice + ',"title":"' + that.data.producData.title + '","thumbnailImage":"' + that.data.producData.thumbnailImage + '","point":' + that.data.point + ',"seckillNum":' + that.data.producData.seckillLimitNum + '}]';
            }
            console.info(plist);
            //此处跳转到修改订单页面
            that.setData({
              pAndNList: plist,
            })
            var addrId= 0;
            if (that.data.addressList[that.data.index]===undefined){
              addrId = 0
            } else {
              addrId = that.data.addressList[that.data.index].addrId
            }

            if (that.data.type == 2 && that.data.buyMethod == 1) {
              if (that.data.typeShow == 2) {//开团价格
                wx.navigateTo({
                  url: '/pages/confirmOrder/confirmOrder?userId=' + this.data.producData.userId + '&pAndNList=' + that.data.pAndNList + '&addrId=' + addrId + '&index=' + that.data.index + '&type=2&typeShow=' + that.data.typeShow
                })
              } else {
                wx.navigateTo({
                  url: '/pages/confirmOrder/confirmOrder?userId=' + this.data.producData.userId + '&pAndNList=' + that.data.pAndNList + '&addrId=' + addrId + '&index=' + that.data.index + '&type=2&typeShow=0'
                })
              }

            } else {
              wx.navigateTo({
                url: '/pages/confirmOrder/confirmOrder?userId=' + this.data.producData.userId + '&pAndNList=' + that.data.pAndNList + '&addrId=' + addrId + '&index=' + that.data.index + '&type=1'
              })
            }

          }
          that.modal_none();
        } else {
          // 未授权，跳转到授权页面
          if(that.data.type!=2){
            that.setData({
              type:0
            })
          }
          wx.reLaunch({
            url: '/pages/zcuslist/index?productid=' + that.data.productid + '&type=' + that.data.type + "&partnerUserId=" + that.data.partnerUserId
          })
        }
      }
    })
    
  },
  // 弹出
  modal_show: function (e) {
    var that = this;
    var flag = e.currentTarget.dataset.flag;
    var type1 = e.currentTarget.dataset.type;
    var buyMethod = e.currentTarget.dataset.buymethod;
    that.setData({
      buyMethod: buyMethod
    });
    that.setData({
      flag: flag,
      choose_modal: "block",
      typeShow: type1
    });
  },
  //消失
  modal_none: function () {
    this.setData({
      choose_modal: "none",
      choose1_modal: "none",
      choose2_modal: "none",
      num:1,
    });
  },

  // 弹出
  modal_s: function (e) {
    var flag = e.currentTarget.dataset.flag;
    this.setData({
      flag: flag,
      choo_modal: "block",
    });
  },

  // 弹出
  modal_s1: function (e) {
    var flag = e.currentTarget.dataset.flag;
    this.setData({
      flag: flag,
      choose1_modal: "block",
    });
  },
  // 弹出
  modal_s2: function (e) {
    var flag = e.currentTarget.dataset.flag;
    this.setData({
      flag: flag,
      choose2_modal: "block",
    });
  },
  //消失
  modal_n: function () {
    this.setData({
      choo_modal: "none",
      num: 1,
    });
  },
  // 弹出
  quest_s: function (e) {
    var flag = e.currentTarget.dataset.flag;
    this.setData({
      flag: flag,
      quest_modal: "block",
    });
  },
  //消失
  quest_n: function () {
    this.setData({
      quest_modal: "none",
      num: 1,
    });
  },

  /* 点击减号 */
  bindMinus: function () {
    var num = this.data.num;
    // 如果大于1时，才可以减
    if (num > 1) {
      num--;
    }
    // 只有大于一件的时候，才能normal状态，否则disable状态
    var minusStatus = num <=
      1 ? 'disabled' :
      'normal';
    // 将数值与状态写回
    this.setData({
      num: num,
      minusStatus: minusStatus
    });
  },
  //加号
  bindPlus: function (e) {
    var num = this.data.num;
    // 不作过多考虑自增1
    if(num < this.data.count){
      if (this.data.type == 1) {
        if (num < this.data.seckillNum) {
          num++;
        }
      }else{
        num++;
      }
    }
    
    // 只有大于一件的时候，才能normal状态，否则disable状态
    var minusStatus = num <
      1 ? 'disabled' :
      'normal';
    // 将数值与状态写回
    console.info(this.data.producData.seckillLimitNum);
    if (this.data.producData.seckillLimitNum > 0) {
      if (num > this.data.producData.seckillLimitNum) {
        wx.showToast({
          title: '超过限购数量',
          icon: "none"
        })
        return;
      }
    }
    
    this.setData({
      num: num,
      minusStatus: minusStatus
    });
  },

  navBack: function () {
    var that = this;
    if (that.data.back==1) {
      wx.redirectTo({
        url: '/pages/mallPage/mallPage',
      })
    } else {
      wx.navigateBack({

      })
    }
    
  },

  countTime() {
    var that = this;
    var date = new Date();
    var now = date.getTime();
    var endDate = new Date(that.data.seckillEndTime.replace(/\.|\-/g, '/'));//设置截止时间
    var end = endDate.getTime();
    var leftTime = end - now; //时间差                              
    var d, h, m, s, ms;
    if (leftTime >= 0) {
      d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
      h = Math.floor(leftTime / 1000 / 60 / 60 % 24);
      m = Math.floor(leftTime / 1000 / 60 % 60);
      s = Math.floor(leftTime / 1000 % 60);
      ms = Math.floor(leftTime % 1000);
      ms = ms < 100 ? "0" + ms : ms
      s = s < 10 ? "0" + s : s
      m = m < 10 ? "0" + m : m
      h = h < 10 ? "0" + h : h
      that.setData({
        countdown: d + "天" + h + "时" + m + "分" + s +"秒" ,
        d: d,
        h:h,
        m:m,
        s:s
      })
      //递归每秒调用countTime方法，显示动态时间效果
      setTimeout(that.countTime, 100);
    } else {
      console.log('已截止')
      that.setData({
        countdown: '00:00:00'
      })
    }

  },
  //l领取优惠券
  led: function (e) {
    var that = this;
    var productTypeId = e.target.dataset.producttypeid;
    var productId = e.target.dataset.productid;
    wx.request({
      url: app.globalData.url + 'userReceiveCoupon',
      method: 'GET',
      data: {
        userId: wx.getStorageSync("userId"),
        couponId: e.target.dataset.couponid
      },
      success: function (res) {
        if(res.data.result == 0){
          wx.showToast({
            title: ""+res.data.errmsg,
            icon: 'none',
            duration: 1500
          })
        }
        wx.request({
          url: app.globalData.url + "getCouponListBy",
          data: {
            productId: productId,
            productTypeId: productTypeId,
            userId: wx.getStorageSync("userId"),
          },
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {
            that.setData({
              cpdata: res.data.data
            })
            if (res.data.data.length > 1) {
              console.info(111);
              that.setData({
                cpdatathreshold: res.data.data[0].couponProduct.threshold,
                cpdataprice: res.data.data[0].couponProduct.price
              })
            }
            if (res.data.data.length > 2) {
              that.setData({
                cpdatathreshold1: res.data.data[1].couponProduct.threshold,
                cpdataprice1: res.data.data[1].couponProduct.price,
              })
            }
          },
        })
      },
    });
  },
  toDetail:function(e){
    wx.navigateTo({
      url: '/pages/taskDetail/taskDetail?questionnaireid=' + e.currentTarget.dataset.questionnaireid + "&detailtype=2" 
    })
  },
  lookAllEvaluation: function () {//跳转评价页面
    wx.navigateTo({
      url: '/pages/evaluation/evaluation?productid=' + this.data.producData.productId
    })
  },
  specifications: function (e){
    console.log(e.currentTarget.dataset.val)
      this.setData({
        specifications:e.currentTarget.dataset.type,
        parameter: e.currentTarget.dataset.value
      })
  },
  getAddress: function (productId){
    var that = this;
    console.log(that.data.producData)
    wx.request({
      url: app.globalData.url + "getUserAddressList",
      data: {
        userId: wx.getStorageSync("userId"),
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        that.setData({
          addressList:res.data.data
        })
        wx.request({
          url: app.globalData.url + "getTotalFreight",
          data: {
            json: "{'addressId':" + res.data.data[0].addrId + ",'product':[{'productId':" + productId + ",'num':1}]}",
          },
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {
            that.setData({
              freight: res.data.data
            })
          },
        })
      },
    })

  },
  chooseAddr: function (e) {
    var that = this;
    wx.request({
      url: app.globalData.url + "getTotalFreight",
      data: {
        json: "{'addressId':" + that.data.addressList[e.currentTarget.dataset.index].addrId + ",'product':[{'productId':" + that.data.producData.productId + ",'num':1}]}",
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        that.setData({
          freight: res.data.data,
          index:e.currentTarget.dataset.index
        })
      },
    })
  },
  collectProduct:function(){
    var that = this;
    wx.request({
      url: app.globalData.url + "userCollectProduct",
      data: {
        productId: that.data.productId,
        userId: wx.getStorageSync("userId"),
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        if (res.data.result==1){
          wx.showToast({
            title: '收藏成功！',
            icon: "none"
          })
          that.setData({
            collection: 1
          })
        }else{
          wx.showToast({
            title: res.data.errmsg,
            icon: "none"
          })
        }
      },
    })
  },
  goGroup: function (e) {
    var that = this;
    // var plist = '[{"productId":"' + that.data.gropuShopList.product.productId + '","num":' + that.data.num + ',"price":' + that.data.gropuShopList.price + ',"title":"' + that.data.gropuShopList.product.title + '","thumbnailImage":"' + that.data.gropuShopList.product.thumbnailImage + '","point":0}]';
    wx.navigateTo({
      url: '/pages/assembleDetail/assembleDetail?orderId='+e.currentTarget.dataset.orderid+'&share=1&type=2'
    })
  },
  goMore: function () {

    var that = this;
    wx.navigateTo({
      url: '/pages/spellGroup/spellGroup'
    })
  },
  getTimeList: function (endTimeList) {
    var that  = this;
    var daysList=new Array();
    var hoursList = new Array();
    var minutesList = new Array();
    var secondsList = new Array();
   for(var i=0;i<endTimeList.length;i++){
     var sdfDate = endTimeList[i].replace(/\.|\-/g, "/");
     var totalSeconds = new Date(sdfDate) - new Date();
     var days = Math.floor(totalSeconds / (24 * 3600 * 1000));
     var leave1 = totalSeconds % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
     var hours = Math.floor(leave1 / (3600 * 1000));
     if (hours < 10) {
       hours = '0' + hours;
     }
     var leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
     var minutes = Math.floor(leave2 / (60 * 1000));
     if (minutes < 10) {
       minutes = '0' + minutes;
     }
     var leave3 = leave2 % (60 * 1000);
     var seconds = Math.floor(leave3 / 1000);
     if (seconds < 10) {
       seconds = '0' + seconds;
     }
     daysList[i] = days;
     hoursList[i] = hours;
     minutesList[i] = minutes;
     secondsList[i] = seconds;
   }
    that.setData({
      daysList: daysList,
      hoursList: hoursList,
      minutesList: minutesList,
      secondsList: secondsList,
    })
  },
  // 计时器
  interval: function () {
    const that = this;
    if (that.data.gropuShopList!=undefined){
      let timer = setInterval(function () {  // 设置定时器
        var secondsList = that.data.secondsList;
        var minutesList = that.data.minutesList;
        var hoursList = that.data.hoursList;
        var daysList = that.data.daysList;
        for (var i = 0; i < that.data.gropuShopList.length; i++) {
          var seconds = parseInt(secondsList[i]);
          var minutes = parseInt(minutesList[i]);
          var hours = parseInt(hoursList[i]);
          var days = parseInt(daysList[i]);
          seconds--;
          if (seconds <= 0) {
            seconds = 60;
            minutes--;
            if (minutes <= 0) {
              minutes = 59;
              hours--;
              if (hours <= 0) {
                hours = 23;
                days--;
              }
              if (days < 0) {
                clearInterval(timer);
                that.onLoad();
              }
            }
            if (minutes < 10) {
              minutesList[i] = '0' + minutes;
              that.setData({
                minutesList: minutesList
              })
            } else {
              minutesList[i] = minutes;
              that.setData({
                minutesList: minutesList
              })
            }

          }

          if (seconds < 10) {
            // 少于10补零
            secondsList[i] = '0' + seconds;
            that.setData({
              secondsList: secondsList
            })
          } else {
            secondsList[i] = seconds;
            that.setData({
              secondsList: secondsList
            })
          }
          daysList[i] = days;
          that.setData({
            daysList: daysList
          })
          hoursList[i] = hours;
          that.setData({
            hoursList: hoursList
          })
        }
      }, 1000)
    }
  },




  extract:function(){
    var that = this;
    if(that.data.producData.inventoryQuantity == 0){
        wx.showToast({
          title: '该礼品卡已售空',
        })
        return;
    }
    wx.showModal({
      title: '提示',
      content: '确定要提货吗？',
      success: function (sm) {
        if (sm.confirm) {
          // 用户点击了确定 可以调用取消订单的方法了
          wx.request({
            url: app.globalData.url + 'submitOrder', //
            data: {
              type: 7,
              cardNo: that.data.cardNo,//卡号
              pickUpGoodCode: that.data.pickUpGoodCode,//提货码
              address: that.data.address,
              telephone: that.data.telephone,
              username: that.data.username,
              userId: wx.getStorageSync("userId"),
              payChannel: 5005,
            },
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            success: function (res) {
              if (res.data.result == 1) {
                wx.navigateTo({
                  url: '/pages/myOrder/myOrder?type=3'
                })
              }else{
                wx.showToast({
                  title: res.data.errmsg,
                  icon: 'none',
                  duration: 3000
                })
              }
            },
            fail: function (err) {

            },
          })
        }
      }
    });
  },
   //将编码后的八进制的emoji表情重新解码成十六进制的表情字符
   entitiesToUtf16: function (str) {
    return str.replace(/&#(\d+);/g, function (match, dec) {
      let H = Math.floor((dec - 0x10000) / 0x400) + 0xD800;
      let L = Math.floor(dec - 0x10000) % 0x400 + 0xDC00;
      return String.fromCharCode(H, L);
    });
  },
})


